Algorithm to find the slope of a line segment.

Write an algorithm to find the slope of a line segment whose end point coordinates are (x1, y1) and (x2, y2). The algorithm gives output whether the slope is positive, negative or zero. Transform your algorithm into C program.

Here’s a simple algorithm to find the slope of a line segment given its endpoints (x1,y1)(x1,y1) and (x2,y2)(x2,y2). The slope mm is calculated using the formula:

m=(y2−y1)/ (x2−x1)

Algorithm Steps:


 1. Input the coordinates x1x1, y1y1, x2x2, and y2y2.


 2. Check if x1x1 is equal to x2x2:
        If true, the slope is undefined (vertical line).
        If false, calculate the slope using the formula.


 3. Determine the nature of the slope:
        If m>0,  output "Positive slope Positive".
        If m>0,  output "Positive slope Negative".

         If m==0, output "Zero slope".

C Program


Here’s how you can implement the above algorithm in C:

#include 
int main() {
    float x1, y1, x2, y2, slope;
    // Input coordinates
    printf("Enter coordinates (x1, y1, x2, y2): ");
    scanf("%f %f %f %f", &x1, &y1, &x2, &y2);
    // Check for vertical line
    if (x1 == x2) {
        printf("The slope is undefined (vertical line).\n");
    } else {
        // Calculate the slope
        slope = (y2 - y1) / (x2 - x1);
        // Determine the nature of the slope
        if (slope > 0) {
            printf("Positive slope\n");
        } else if (slope < 0>           
             printf("Negative slope\n");
        } else {
            printf("Zero slope\n");
        }
    }
    return 0;
}


Explanation of the C Program:


    The program prompts the user to enter the coordinates of the two endpoints.
    It checks if the line is vertical by comparing x1x1 and x2x2.
    If the line is not vertical, it calculates the slope and checks its value to determine if it's positive, negative, or zero, then outputs the result accordingly.

You can compile and run this code using any standard C compiler.

  • To Share this Blog, Choose your plateform


Write your Testimonial

Your review is very precious for us.


Rating: